<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="translate(title)"
    width="800px"
    @close="close"
  >
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <!-- <el-form-item label="父节点" prop="parentName">
        <el-select v-model="form.parentId" placeholder="请选择父节点">
          <el-option
            :label="form.parentName"
            style="height: auto; padding: 0"
            :value="form.parentId"
          >
            <el-tree
              ref="treeRef"
              :data="treeData"
              default-expand-all
              :props="defaultProps"
              @node-click="handleNodeClick"
            />
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item :label="translate('部门编码')" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item :label="translate('部门名称')" prop="fullName">
        <el-input v-model="form.fullName" />
      </el-form-item>
      <el-form-item :label="translate('上级公司/部门')">
        <el-tree-select
          v-model="form.companyId"
          :check-strictly="true"
          :data="tree"
          node-key="id"
          :props="defaultProps"
          :render-after-expand="false"
          show-checkbox
        />
      </el-form-item>
      <el-form-item :label="translate('部门简称')" prop="shortName">
        <el-input v-model="form.shortName" />
      </el-form-item>
      <el-form-item :label="translate('部门性质')" prop="nature">
        <el-select v-model="form.nature" :placeholder="translate('请选择')">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="translate('分管总经理')">
        <el-select
          v-model="form.directorName"
          :placeholder="translate('请选择')"
          @change="selectdtFn"
        >
          <el-option
            v-for="item in userData"
            :key="item.UserId"
            :label="item.RealName"
            :value="item.UserId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="translate('联系电话')">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item :label="translate('指定部门经理')">
        <el-select
          v-model="form.depMID"
          collapse-tags
          multiple
          :placeholder="translate('请选择')"
          @change="selectFn"
        >
          <el-option
            v-for="item in userData"
            :key="item.UserId"
            :label="item.RealName"
            :value="item.UserId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="translate('电子邮件')" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item :label="translate('显示顺序')" prop="sortCode">
        <el-input v-model="form.sortCode" />
      </el-form-item>
      <el-form-item :label="translate('选项')" prop="order">
        <el-switch v-model="form.order" active-value="1" inactive-value="0" />
      </el-form-item>
      <el-form-item :label="translate('部门性质')">
        <el-input v-model="form.remark" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">{{ translate('取消') }}</el-button>
      <el-button type="primary" @click="save">
        {{ translate('确定') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doEdit, GetDepartmentInfo } from '@/api/departmentManagement'
  import { getList } from '@/api/userManagement'
  import { prop } from 'dom7'
  import { translate } from '@/i18n'
  export default defineComponent({
    name: 'DepartmentManagementEdit',
    props: {
      tree: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['fetchData'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        defaultProps: {
          children: 'ChildNodes',
          label: 'text',
        },
        treeData: [],
        queryForm: {
          departmentId: 'string',
        },
        options: [
          {
            value: '技术部门',
            label: '技术部门',
          },
          {
            value: '综合性',
            label: '综合性',
          },
        ],
        form: {
          depMName: [],
          depMID: [],
        },
        userData: [],
        rules: {
          parentName: [
            { required: true, trigger: 'blur', message: '请选择父节点' },
          ],
          code: [
            { required: true, trigger: 'blur', message: '请输入部门编码' },
          ],
          fullName: [
            { required: true, trigger: 'blur', message: '请输入部门名称' },
          ],
          shortName: [
            { required: true, trigger: 'blur', message: '请输入部门简称' },
          ],
          irectorName: [
            { required: true, trigger: 'blur', message: '请输入分管总经理' },
          ],
          phone: [
            { required: true, trigger: 'blur', message: '请输入联系电话' },
          ],
          email: [
            { required: true, trigger: 'blur', message: '请输入电子邮件' },
          ],
          fax: [{ required: true, trigger: 'blur', message: '请输入传真' }],
          depMName: [
            { required: true, trigger: 'blur', message: '请输入指定部门经理' },
          ],
          directorName: [
            { required: true, trigger: 'blur', message: '请输入分管经理' },
          ],
          sortCode: [
            { required: true, trigger: 'blur', message: '请输入显示顺序' },
          ],
          remark: [
            { required: true, trigger: 'blur', message: '请输入公司描述' },
          ],
        },
        title: '',
        dialogFormVisible: false,
      })

      watch(
        () => state.form.companyId,
        () => {
          userList()
        }
      )
      const fetchData = async () => {
        const {
          data: { data },
        } = await GetDepartmentInfo(state.queryForm)
        data.depMID = data.depMID ? data.depMID.split(',') : []
        console.log(data.depMID)
        state.form = data
      }
      const userList = async () => {
        const params = {
          companyId: state.form.companyId,
          export: true,
          pageNo: 1,
          pageSize: 20,
          wheres: `[{"name":"CompanyId","value":"${state.form.companyId}","displayType":"equal"}]`,
        }
        const data = await getList(params)
        if (data.code === '200') {
          state.userData = data.data.rows
        }
      }
      const selectdtFn = (val) => {
        console.log(val)
        if (val) {
          state.userData.map((item) => {
            if (item.UserId === val) {
              state.form.directorName = item.RealName
              state.form.directorId = item.UserId
            }
          })
        }
      }

      const selectFn = (val) => {
        console.log(val)
        console.log(state.form.depMID)
        state.form.depMID = []
        state.form.depMName = []
        if (val) {
          val.map((itemlist) => {
            state.userData.map((item) => {
              if (itemlist === item.UserId) {
                state.form.depMID.push(item.UserId)
                state.form.depMName.push(item.RealName)
              }
            })
          })
        }
      }
      const handleNodeClick = (node) => {
        state.form.parentName = node.name
      }
      const showEdit = (row, type) => {
        if (type != 'edit') {
          state.title = '添加'
          state.queryForm.departmentId = row || 0
        } else {
          state.title = '编辑'
          state.queryForm = {
            departmentId: row.DepartmentId,
          }
          fetchData()
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.dialogFormVisible = false
      }
      const save = () => {
        state.form.parentId = 0
        state['formRef'].validate(async (valid) => {
          if (valid) {
            // state.form.depMName = state.form.depMName
            console.log(state.form.depMID)
            console.log(state.form.depMName)
            state.form.depMID = state.form.depMID
              ? Array.isArray(state.form.depMID)?state.form.depMID.join(','):state.form.depMID
              : ''
            state.form.depMName = state.form.depMName
              ? Array.isArray(state.form.depMName)?state.form.depMName.join(','):state.form.depMName
              : ''
            const { message } = await doEdit(state.form)
            $baseMessage(message, 'success', 'vab-hey-message-success')
            emit('fetchData')
            close()
          }
        })
      }

      return {
        ...toRefs(state),
        handleNodeClick,
        showEdit,
        close,
        save,
        translate,
        userList,
        selectFn,
        selectdtFn,
      }
    },
  })
</script>
<style scoped>
  .el-form {
    display: flex;
    flex-flow: wrap;
    justify-content: left;
  }
  .el-form >>> .el-input {
    width: 234px !important;
  }
  .el-form-item {
    width: 380px;
  }
</style>
